<!--
 * @Description: 材料管理
 * 
 * @Author: XiongYaoYuan<xiongyaoyuan>
 * @Date: 2023-06-27 20:16:06
 * @FilePath: /yuxiuproweb/src/views/material/inventory/index.vue
-->
<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="仓库名称" prop="repositoryName">
        <el-input
          v-model="queryParams.repositoryName"
          placeholder="请输入仓库名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="存货编码" prop="inventoryCode">
        <el-input
          v-model="queryParams.inventoryCode"
          placeholder="请输入存货编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="存货名称" prop="frbaicName">
        <el-input
          v-model="queryParams.frbaicName"
          placeholder="请输入存货名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品类型" prop="ctype">
        <el-select
          v-model="queryParams.ctype"
          clearable
          placeholder="请选择产品类型"
          @change="handleQuery"
        >
          <el-option label="窗帘" :value="2"> </el-option>
          <el-option label="墙布" :value="1"> </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="批号" prop="batchNumber">
        <el-input
          v-model="queryParams.batchNumber"
          placeholder="请输入批号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="供应商" prop="supplier">
        <el-input
          v-model="queryParams.supplier"
          placeholder="请输入供应商"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="供应商型号" prop="specification" label-width="110px">
        <el-input
          v-model="queryParams.specification"
          placeholder="请输入供应商型号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="库存" prop="specification">
         <el-select
          v-model="queryParams.ctype"
          clearable
          placeholder="请选择库存"
          @change="handleQuery"
        >
          <el-option label="空" :value="2"> </el-option>
          <el-option label="" :value="1"> </el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item label="日期" prop="createDateObj">
        <el-date-picker
          align="center"
          style="width: 240px"
          v-model="createDateObj"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          format="yyyy-MM-dd"
          @change="handleQuery"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item prop="isEmpty" label-width="0">
        <el-checkbox
          v-model="queryParams.isEmpty"
          style="margin-right: 10px"
          @change="handleQuery"
        >
          <span style="font-size: 13px">过滤空库存</span>
        </el-checkbox>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
        <el-button-group style="margin-left: 10px">
          <el-button
            :type="!queryParams.accurate ? 'primary' : 'default'"
            @click="queryParams.accurate = false"
            size="mini"
            >模糊</el-button
          >
          <el-button
            :type="queryParams.accurate ? 'primary' : 'default'"
            @click="queryParams.accurate = true"
            size="mini"
            >精确</el-button
          >
        </el-button-group>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['md:inventory:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['md:inventory:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['md:inventory:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['md:inventory:export']"
          >导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          >期初导入</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain size="mini" @click="handleAllocation"
          >仓库调拨</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain size="mini" @click="handlePrintCode"
          >条码打印</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="inventoryList"
      @selection-change="handleSelectionChange"
      :max-height="maxHeight"
      border
      :row-style="{ height: '20px' }"
      :cell-style="{ padding: '0px', 'font-size': '14px' }"
      size="mini"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="产品类型" align="center" prop="ctype">
        <template slot-scope="scope">
          <span v-if="scope.row.ctype == 2">窗帘</span>
          <span v-if="scope.row.ctype == 1">墙布</span>
        </template>
      </el-table-column>
      <el-table-column label="日期" align="center" prop="createdTime" />
      <el-table-column label="条码" align="center" prop="barcode" />
      <el-table-column label="卷号" align="center" prop="oid" />
      <el-table-column label="到货单号" align="center" prop="arrivalnumber" />
      <el-table-column label="到货日期" align="center" prop="Arrivaldate" />
      <el-table-column label="存货编码" align="center" prop="inventoryCode" />
      <el-table-column label="存货名称" align="center" prop="frbaicName" />
      <el-table-column label="供应商型号" align="center" prop="specification" />
      <el-table-column label="批号" align="center" prop="batchNumber" />
      <el-table-column label="供应商" align="center" prop="supplier" />
      <el-table-column label="验布数量" align="center" prop="unit" />
      <el-table-column
        label="现存数量"
        align="center"
        prop="inventoryQuantity"
      />
      <el-table-column label="计划用量" align="center" prop="freezenum" />
      <el-table-column
        label="可用数量"
        align="center"
        prop="availableQuantity"
      />
      <el-table-column label="仓库名称" align="center" prop="repositoryName" />
      <el-table-column label="货位" align="center" prop="goodsallocation" />
      <el-table-column label="状态" align="center" prop="status" />
      <el-table-column label="是否防水" align="center" prop="iswaterproof" />
      <el-table-column label="门幅" align="center" prop="doorwidth" />

      <el-table-column label="验货状态" align="center" prop="inspectionStatus">
        <template slot-scope="{ row }">
          {{
            row.inspectionStatus == "0"
              ? "未验货"
              : row.inspectionStatus == "1"
              ? "已验货"
              : row.inspectionStatus == "2"
              ? "退货"
              : ""
          }}
        </template>
      </el-table-column>
      <el-table-column label="疵点" align="center" prop="defect" />
      <el-table-column label="左空" align="center" prop="leftempty" />
      <el-table-column label="右空" align="center" prop="rightempty" />
      <el-table-column label="花到花" align="center" prop="flowertoflower" />
      <el-table-column label="备注[批次]" align="center" prop="notespc" />
      <el-table-column label="加工商" align="center" prop="converter" />
      <el-table-column label="是否出入库" align="center" prop="isinputout" />
      <el-table-column label="来源" align="center" prop="source" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="180"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['md:inventory:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleQRCode(scope.row)"
            v-hasPermi="['md:inventory:edit']"
            >二维码</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['md:inventory:remove']"
            style="color: #ff4949"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改材料库存对话框 -->
    <el-dialog
      :close-on-click-modal="false"
      :title="title"
      :visible.sync="open"
      width="700px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="仓库名称" prop="repositoryName">
              <el-input
                v-model="form.repositoryName"
                placeholder="请输入仓库名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="存货编码" prop="inventoryCode">
              <el-input
                v-model="form.inventoryCode"
                placeholder="请输入存货编码"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="存货名称" prop="frbaicName">
              <el-input
                v-model="form.frbaicName"
                placeholder="请输入存货名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商型号" prop="specification">
              <el-input
                v-model="form.specification"
                placeholder="请输入供应商型号"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="主计量单位" prop="unit">
              <el-input v-model="form.unit" placeholder="请输入主计量单位" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="批号" prop="batchNumber">
              <el-input v-model="form.batchNumber" placeholder="请输入批号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="现存数量" prop="inventoryQuantity">
              <el-input
                v-model="form.inventoryQuantity"
                placeholder="请输入现存数量"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="可用数量" prop="availableQuantity">
              <el-input
                v-model="form.availableQuantity"
                placeholder="请输入可用数量"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="疵点数" prop="defect">
              <el-input v-model="form.defect" placeholder="请输入疵点数" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="验货状态" prop="inspectionStatus">
              <el-select
                v-model="form.inspectionStatus"
                placeholder="请选择验货状态"
                style="width: 100%"
              >
                <el-option label="未验货" :value="0" />
                <el-option label="已验货" :value="1" />
                <el-option label="退货" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 二维码 -->
    <QRCodeView v-if="code.show" :show.sync="code.show" v-bind="code" />
    <!-- 仓库调拨 -->
    <el-dialog
      :close-on-click-modal="false"
      title="仓库调拨"
      :visible.sync="openAllocation"
      width="400px"
      append-to-body
    >
      <el-form ref="allocationForm" label-width="60px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="仓库" prop="warehouseName">
              <el-select
                style="width: 100%"
                v-model="allocationForm.warehouseId"
                clearable
                filterable
                placeholder="请选择仓库"
                remote
                reserve-keyword
                :remote-method="getWarehouseList"
                @change="handleWarehouseChange"
                @clear="
                  allocationForm.warehouseName = '';
                  allocationForm.warehouseId = '';
                "
              >
                <el-option
                  v-for="item in warehouseList"
                  :key="item.warehouseId"
                  :label="item.warehouseName"
                  :value="item.warehouseId"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="货位" prop="inventoryCode">
              <el-select
                style="width: 100%"
                v-model="allocationForm.areaId"
                clearable
                filterable
                placeholder="请选择货位"
                remote
                reserve-keyword
                :remote-method="getAreaList"
                @change="handleAreaChange"
                @clear="
                  allocationForm.areaName = '';
                  allocationForm.areaId = '';
                "
              >
                <el-option
                  v-for="item in areaList"
                  :key="item.areaName"
                  :label="item.areaName"
                  :value="item.areaId"
                >
                  <span style="float: left">{{ item.areaName }}</span>
                  <span
                    style="
                      float: right;
                      text-align: right;
                      color: #8492a6;
                      font-size: 13px;
                    "
                  >
                    {{ item.warehouseName }}</span
                  >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAllocationForm"
          >确 定</el-button
        >
        <el-button @click="openAllocation = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 期初导入 -->
    <el-dialog
      :close-on-click-modal="false"
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <print-view
      v-if="print.show"
      :show.sync="print.show"
      v-bind="print"
    ></print-view>
  </div>
</template>

<script>
import {
  listInventory,
  getInventory,
  delInventory,
  addInventory,
  updateInventory,
  transferInventory,
} from "@/api/material/inventory";
import QRCodeView from "./mods/QRCode.vue";
import commonMix from "@/utils/mixins/common";
import { getWarehouseLocationList } from "@/api/mes/wm/warehouseLocation";
import { listWarehouse } from "@/api/mes/wm/warehouse";
import { getToken } from "@/utils/auth";
import PrintView from "./mods/print.vue";
export default {
  name: "Inventory",
  mixins: [commonMix],
  components: {
    QRCodeView,
    PrintView,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 材料库存表格数据
      inventoryList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 100,
        repositoryName: null,
        inventoryCode: null,
        frbaicName: null,
        specification: null,
        unit: null,
        batchNumber: null,
        inventoryQuantity: null,
        availableQuantity: null,
        ctype: null,
        accurate: false,
        isEmpty: true,
      },
      createDateObj: [],
      selRow: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        repositoryName: [
          { required: true, message: "仓库名称不能为空", trigger: "change" },
        ],
      },
      code: {
        show: false,
        data: null,
      },
      openAllocation: false,
      allocationForm: {
        areaId: "",
        areaName: "",
        warehouseName: "",
        warehouseId: "",
      },
      areaList: [],
      warehouseList: [],
      // 导入参数
      upload: {
        // 是否显示弹出层（收入导入）
        open: false,
        // 弹出层标题（收入导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的收入数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/md/inventory/importData",
      },
      print: {
        show: false,
        type: "0",
        data: null,
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询材料库存列表 */
    getList() {
      this.loading = true;
      const params = {
        ...this.queryParams,
        startDate: this.createDateObj?.[0] || null,
        endDate: this.createDateObj?.[1] || null,
      };
      params.isEmpty = this.queryParams.isEmpty ? "0" : null;
      listInventory(params).then((response) => {
        this.inventoryList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        fabricInventoryId: null,
        repositoryName: null,
        inventoryCode: null,
        frbaicName: null,
        specification: null,
        unit: null,
        batchNumber: null,
        inventoryQuantity: null,
        availableQuantity: null,
        defect: null,
        inspectionStatus: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.createDateObj = [];
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.fabricInventoryId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
      this.selRow = selection;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加材料库存";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const fabricInventoryId = row.fabricInventoryId || this.ids;
      getInventory(fabricInventoryId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改材料库存";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.fabricInventoryId != null) {
            updateInventory(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInventory(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const fabricInventoryIds = row.fabricInventoryId || this.ids;
      this.$modal
        .confirm(
          '是否确认删除材料库存编号为"' + fabricInventoryIds + '"的数据项？'
        )
        .then(function () {
          return delInventory(fabricInventoryIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "md/inventory/export",
        {
          ...this.queryParams,
        },
        `inventory_${new Date().getTime()}.xlsx`
      );
    },
    // 生成二维码
    handleQRCode(row) {
      getInventory(row.fabricInventoryId).then(({ data }) => {
        console.log(data);
        this.code = {
          show: true,
          data,
        };
      });
    },
    submitAllocationForm() {
      var arrData = [];
      for (let i = 0; i < this.selRow.length; i++) {
        const item = this.selRow[i];
        var obj = {
          areaId: this.allocationForm.areaId,
          goodsallocation: this.allocationForm.areaName,
          warehouseId: this.allocationForm.warehouseId,
          repositoryName: this.allocationForm.warehouseName,
          fabricInventoryId: item.fabricInventoryId,
        };
        arrData.push(obj);
      }
      transferInventory(arrData).then((res) => {
        if (res.code == 200) {
          this.$message.success("操作成功");
          this.getList();
          this.openAllocation = false;
        }
      });
    },
    // 仓库调拨
    handleAllocation() {
      if (!this.selRow.length) {
        this.$message.error("请勾选库存");
        return;
      }
      (this.allocationForm = {
        areaId: "",
        areaName: "",
        warehouseName: "",
        warehouseId: "",
        fabricInventoryId: "",
      }),
        (this.openAllocation = true);
      this.getWarehouseList();
      this.getAreaList();
    },
    handleWarehouseChange(val) {
      var index = this.warehouseList.findIndex((a) => a.warehouseId == val);
      if (index != -1) {
        this.allocationForm.warehouseName =
          this.warehouseList[index].warehouseName;
        this.allocationForm.warehouseId = this.warehouseList[index].warehouseId;
        this.getAreaList();
      }
    },
    getWarehouseList(warehouseName = "") {
      var queryParams = {
        pageNum: 1,
        pageSize: 1000,
        warehouseName: warehouseName,
        // enableFlag: "1",
      };
      listWarehouse(queryParams).then((response) => {
        this.warehouseList = response.rows;
      });
    },
    handleAreaChange(val) {
      var index = this.areaList.findIndex((a) => a.areaId == val);
      if (index != -1) {
        this.allocationForm.warehouseName = this.areaList[index].warehouseName;
        this.allocationForm.warehouseId = this.areaList[index].warehouseId;
        this.allocationForm.areaName = this.areaList[index].areaName;
        this.allocationForm.areaId = this.areaList[index].areaId;
      }
    },
    getAreaList(areaName = "") {
      var queryParams = {
        pageNum: 1,
        pageSize: 1000,
        areaName: areaName,
        enableFlag: "1",
        warehouseId: this.allocationForm.warehouseId,
      };
      getWarehouseLocationList(queryParams).then((res) => {
        this.areaList = res.rows;
      });
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    //期初导入
    handleImport() {
      this.upload.title = "期初导入";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    handlePrintCode() {
      if (!this.selRow.length) {
        this.$message.error("请勾选打印内容");
        return;
      }
      this.print = {
        show: true,
        type: "0",
        data: this.selRow,
      };
    },
  },
};
</script>
